import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const Category = () => import('@/views/category')
const SubCategory = () => import('@/views/category/SubCategory.vue')
const Goods = () => import('@/views/goods')
const Login = () => import('@/views/login')
const Cart = () => import('@/views/cart')
const Checkout = () => import('@/views/member/pay/checkout.vue')
const PayIndex = () => import('@/views/member/pay')
const PayResult = () => import('@/views/member/pay/result')
const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/detail')

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: 'category/:id', component: Category },
      { path: 'category/sub/:id', component: SubCategory },
      { path: 'product/:id', component: Goods },
      { path: 'cart', component: Cart },
      { path: 'member/checkout', component: Checkout },
      { path: 'member/pay', component: PayIndex },
      { path: 'pay/callback', component: PayResult },
      {
        path: 'member',
        component: MemberLayout,
        children: [
          { path: '/member', component: MemberHome },
          // { path: '/member/order', component: MemberOrder },
          // { path: '/member/order/:id', component: MemberOrderDetail }
          // 解决菜单激活问题
          {
            path: '/member/order',
            component: {
              render: () => h(<RouterView />)
            },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }
            ]
          }
        ]
      }
    ]
  },
  { path: '/login', component: Login }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 切换路由是滚动到最顶部
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    return next(`/login?redirectUrl=${encodeURIComponent(to.fullPath)}`)
  }
  next()
})

export default router
